import React from 'react';
import echarts from 'echarts';
import BreadcrumbCustom from '../../BreadcrumbCustom';
import { Row, Col, Form, Input, DatePicker, Button, Tabs, Table, Select, message, Spin } from 'antd';
import { getClassifiesAll } from '../../../Server/SystemManger';
import moment from 'moment';
import qs from 'qs';
import * as Request from '../../../Server/Statistics';
import * as Constant from '../../../common/const';
import * as Utils from '../../../common/utils';
import Echarts from './Echarts';
require('../sysinfo/sysinfo.css');

const FormItem = Form.Item;
const { MonthPicker } = DatePicker;
const TabPane = Tabs.TabPane;
const dateFormat = 'YYYY-MM';
const titleDateFmt = 'YYYY年MM月';
let sysCompany = {};//当前人所在分部信息
let partState = false;
const defaultQuery = { queryMonth: moment(new Date()).format(dateFormat) };
let dailyDefaultQuery = { ...defaultQuery };
const Option = Select.Option;
let flag = true;

class RequestInfo extends React.Component {
    constructor(props) {
        super(props);
        sysCompany = JSON.parse(localStorage.getItem('user')).sysCompany;//当前人所在分部信息
        flag = Utils.objectIsNull(sysCompany);
        partState = flag && sysCompany.id == 1;
        flag && (dailyDefaultQuery = { ...dailyDefaultQuery, startIp: sysCompany.startIp, endIp: sysCompany.endIp });
        this.state = {
            commonOption: {
                toolbox: {
                    show: true,
                    right: '9.4%',
                    feature: {
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                color: ['#53ADFB'],
                legend: {
                    selectedMode: false,
                    bottom: 0,
                    show: false,
                },
                grid: {
                    left: '10%',//因旋转导致名字太长的类目造成遮蔽，可以配合这两个属性
                    bottom:'10%'// 分别表示：距离左边距和底部的距离，具体数值按实际情况调整
                },
            },
            option: {},
            date: undefined,
            activeKey: partState ? '1' : '2',
            currentCompany: flag && sysCompany.name,
            allDataSource: [],
            currentDataSource: [],
            partNameData: [],
            startIp: flag && sysCompany.startIp, //分部管理起始ip
            endIp: flag && sysCompany.endIp, //分部管理结束ip
            sumLoading: false, //总部loading
            partLoading: false, //分部loading
            sumMaxData: '', //总部数据最大值
            partMaxData: '' //分部数据最大值
        }
    }

    componentDidMount() {
        if(!flag) return;
        if (sysCompany.id == 1) {
            this.fetchData();
            this.getPartName();
        } else {
            this.fetchDailyData();
        }
    }

    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }

    fetchData = (params = defaultQuery) => {
        const _this = this;
        this.setState({
            sumLoading: true
        })
        Request.allRequestMonthly(qs.stringify(params)).then(res => {
            if (res && Constant.REQUEST_SUCCESS == res.code) {
                const result = _this.dealResponseData(res.data.points);
                const seriesName = ['请求量'];
                const option = _this.getOption(`请求信息(${moment(params.queryMonth).format(titleDateFmt)})`, '分级', '请求信息量', ...result, seriesName[0]);
                const sumMaxData = Math.max(...result[1]);
                option.tooltip = {
                    trigger: 'axis',
                    formatter: `${moment(params.queryMonth).format('YYYY年MM月')}<br/>请求信息<br/>分部名称:{b}<br/>请求量:{c}`
                };
                option.legend = {
                    selectedMode: false,
                    data: seriesName,
                    /*left: '48%',*/
                    top: 30,
                    align:'left'
                };
                _this.setState({ option: option, allDataSource: res.data.points, sumLoading: false, sumMaxData });
            } else {
                this.setState({ sumLoading: false})
                res && res.code !== Constant.REQUEST_UNAUTHORIZED && message.error(res.msg)
            }
        });
    }

    fetchDailyData = (params = dailyDefaultQuery) => {
        this.setState({
            partLoading: true
        })
        Request.currentRequestDaily(qs.stringify(params)).then(res => {
            if (res && Constant.REQUEST_SUCCESS == res.code) {
                const result = this.dealResponseData(res.data.points, false);
                const seriesName = ['请求量'];
                const option = this.getOption(`请求信息(${moment(params.queryMonth).format(titleDateFmt)})`, '日期', '请求信息量', ...result, seriesName[0]);
                const partMaxData = Math.max(...result[1]);
                option.tooltip = {
                    trigger: 'axis',
                    formatter: `${moment(params.queryMonth).format('YYYY年MM月')}{b}日<br/>{a}:{c}`
                };
                option.legend = {
                    selectedMode: false,
                    data: seriesName,
                    /*right: '9.4%',*/
                    top: 30,
                    align:'left'
                };
                this.setState({ option: option, currentDataSource: res.data.points, partLoading: false, partMaxData });
            } else {
                this.setState({
                    partLoading: false
                })
                res && res.code !== Constant.REQUEST_UNAUTHORIZED && message.error(res.msg)
            }
        });
    }
    dealResponseData = (data = [], flag = true) => {
        let xData = [], yData = [];
        data.map(item => {
            xData.push(flag ? item.x : item.x.substring(item.x.length - 2, item.x.length));
            yData.push(item.y)
        });
        return [xData, yData];
    }
    getOption = (title, xName, yName, xData, yData, seriesName) => {
        let maxValue = Utils.GetMaxValue(yData);
        return {
            title: {
                text: title,
                left: 'center',
            },
            xAxis: {
                name: xName,
                type: 'category',
                boundaryGap: true, //图形两边留白, false则不留白
                data: xData,
                axisLabel: Constant.AXIS_LABEL,
                axisTick: {
                    // alignWithLabel: true, //留白后让刻度轴在标签名下
                }
            },
            yAxis: {
                name: yName,
                type: 'value',
                minInterval: 1,
                interval: Utils.GetInterval(maxValue),
                max: (value)=> {
                    return maxValue;
                    // return Math.ceil(value.max*1.2);
                },
                axisLabel: {
                    showMaxLabel: true
                },
                nameTextStyle: {
                    padding: [0, 0, 15, 0]
                },
                splitLine:{
                    lineStyle:{
                        type:'dashed'
                    }
                }
            },
            series: [{
                name: seriesName,
                smooth: true,
                data: yData,
                type: 'line',
                barWidth: Constant.STATISTIC_BAR_WIDTH,
                symbolSize: 8,
                // barGap:'-100%',
                // barCategoryGap:'40%',
                label: {
                    normal: Constant.LABEL_NORMAL
                },
                itemStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(
                            0, 0, 0, 1,
                            [
                                {offset: 0, color: '#4fc9e7'},
                                {offset: 1, color: '#61B1F8'},
                                {offset: 1, color: '#61B1F8'}
                            ]
                        ),
                    }
                },
                lineStyle: {
                    width: Constant.STATISTIC_LINE_WIDTH,
                }
            }],
            dataZoom : Constant.dataZoom(yData)
        };
    }
    search = (e) => {
        e.preventDefault();
        const { startIp, endIp } = this.state;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.queryMonth = moment(values.queryMonth).format('YYYY-MM');
                delete values['partName'];
                if ('1' == this.state.activeKey) {
                    delete values['startIp'];
                    delete values['endIp'];
                    this.fetchData(values);
                } else {
                    values.startIp = values.startIp ? values.startIp : startIp;
                    values.endIp = values.endIp ? values.endIp : endIp;
                    this.fetchDailyData(values);
                }

            }
        });
    }
    reset = (activeKey = this.state.activeKey) => {
        if (typeof activeKey == 'object') {
            activeKey = this.state.activeKey;
        }
        const resetValues = {
            distNum: undefined,
            version: undefined,
            sn: undefined,
            queryMonth: moment(defaultQuery.queryMonth, dateFormat),
            startIp: partState?"":dailyDefaultQuery.startIp,
            endIp: partState?"":dailyDefaultQuery.endIp,
            partName: partState?sysCompany.id:''
        }
        this.setState({
            startIp: dailyDefaultQuery.startIp,
            endIp: dailyDefaultQuery.endIp,
        })
        this.props.form.setFieldsValue({ ...resetValues });
        '1' == activeKey ? this.fetchData() : this.fetchDailyData();
    }
    changeTab = (activeKey) => {
        this.setState({ activeKey });
        this.reset(activeKey);
    }

    //导出方法
    export = (data, headers, maxData) => {
        const [title1, title2] = headers;
        let _data = [];
        for (var i = 0; i < data.length; i++) {
            let temp = {};
            temp[title1] = data[i].x;
            temp[title2] = data[i].y;
            _data.push(temp);
        }
        Utils.outPutExcel(headers, _data, '请求信息', maxData);
    }

    //获取分部名数据
    getPartName = () => {
        getClassifiesAll().then(res => {
            if (res && res.code == Constant.REQUEST_SUCCESS) {
                const data = res.data
                this.setState({
                    partNameData: data,
                });
            } else {
                res && res.code !== Constant.REQUEST_UNAUTHORIZED && message.error(res.msg);
            }
        });
    }

    //禁止时间
    disabledDate = (current) => {
        // Can not select days before today and today
        return current.valueOf() > Date.now();
    }

    //分部名选择事件
    partNameSelect = (value, option) => {
        this.props.form.setFieldsValue({ startIp: '', endIp: '' });
        this.setState({
            startIp: option.props.startip,
            endIp: option.props.endip
        })
    }

    //校验起始ip
    checkStartIP = (rule, value, callback) => {
        let { startIp, endIp } = this.state;
        if (value == '' || value == undefined) {
            if (sysCompany.id == 1) {
                callback();
                return;
            } else {
                callback('请输入起始IP地址！');
                return;
            }
        }
        if (!Utils.checkIP(value)) {
            callback('请输入正确地IP地址！');
            return;
        } else if (!Utils.checkIPValue(value, startIp, endIp)) {
            callback('请输入分部范围内的IP地址！');
            return;
        } else if (!Utils.checkIPCount(this.props.form.getFieldValue("startIp"), this.props.form.getFieldValue("endIp"))) {
            callback('起始IP不能大于结束IP');
            return;
        }
        if (this.props.form.getFieldValue('endIp') && this.props.form.getFieldError('endIp')) {
            this.props.form.validateFields(['endIp'], { force: true });
        }
        callback();
    }

    //校验结束ip
    checkEndIP = (rule, value, callback) => {
        let { startIp, endIp } = this.state;
        if (value == '' || value == undefined) {
            if (sysCompany.id == 1) {
                callback();
                return;
            } else {
                callback('请输入结束IP地址！');
                return;
            }
        }
        if (!Utils.checkIP(value)) {
            callback('请输入正确地IP地址！');
            return;
        } else if (!Utils.checkIPValue(value, startIp, endIp)) {
            callback('请输入分部范围内的IP地址！');
            return;
        } else if (!Utils.checkIPCount(this.props.form.getFieldValue("startIp"), this.props.form.getFieldValue("endIp"))) {
            callback('结束IP不能小于起始IP');
            return;
        }
        if (this.props.form.getFieldValue('startIp') && this.props.form.getFieldError('startIp')) {
            this.props.form.validateFields(['startIp'], { force: true });
        }
        callback();
    }

    validateSn = (rule, value, callback) => {
        if (Utils.CheckSnFunc(value)) {
            callback('序列号存在非法字符,请重新输入');
            return;
        }
        callback();
        return;
    }

    validateVersion = (rule, value, callback) => {
        if (Utils.CheckSnFunc(value)) {
            callback('版本号存在非法字符,请重新输入');
            return;
        }
        callback();
        return;
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const { partNameData, sumLoading, partLoading, sumMaxData, partMaxData } = this.state;
        const partNameOptions = partNameData.map(d => <Option value={d.id} endip={d.endIp} startip={d.startIp} >{d.name}</Option>);
        const columnAll = [{
            title: '分部名称',
            dataIndex: 'x',
            align: 'center',
            width: '60%',
            key: 'x'
        },
        {
            title: '请求量',
            dataIndex: 'y',
            align: 'center',
            width: '40%',
            key: 'y'
        },];
        const columnCurrent = [{
            title: '日期',
            dataIndex: 'x',
            align: 'center',
            width: '60%',
            render: (text) => moment(text).format('YYYY-MM-DD')
        },
        {
            title: '请求量',
            dataIndex: 'y',
            align: 'center',
            width: '40%'
        },];
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 7 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 17 },
            },
        };
        return (
            <div>
                <Row>
                    <BreadcrumbCustom first={'请求信息'} />
                </Row>
                {flag && <Tabs activeKey={this.state.activeKey} type={'card'} onChange={this.changeTab}>
                    {sysCompany.id == 1 && <TabPane tab={'总部权限'} key={'1'}>
                    <Spin spinning={sumLoading} >
                        <Form onSubmit={this.search}>
                            <Row>
                                <Col span={6}>
                                    <FormItem label={'通道号'} {...formItemLayout}>
                                        {getFieldDecorator('distNum')(
                                            <Input maxLength={255} />
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={6}>
                                    <FormItem label={'版本号'} {...formItemLayout}>
                                        {getFieldDecorator('version')(
                                            <Input maxLength={255} />
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={6}>
                                    <FormItem label={'序列号'} {...formItemLayout}>
                                        {getFieldDecorator('sn')(
                                            <Input maxLength={255} />
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={6}>
                                    <FormItem
                                        label={'时间'}
                                        {...formItemLayout}
                                    >
                                        {getFieldDecorator('queryMonth', {
                                            initialValue: moment(defaultQuery.queryMonth, dateFormat)
                                        })(
                                            <MonthPicker
                                                disabledDate={this.disabledDate}
                                                format={'YYYY-MM'}
                                                allowClear={false}
                                                style={{ width: '90%' }}
                                            />
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...Constant.BUTTONSPAN} className='count-button-margin'>
                                    <FormItem>
                                        <Button type="primary" htmlType="submit" >查询</Button>
                                        <Button type="default" onClick={this.reset} >重置</Button>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                        <Row>
                            <Col span={19} style={{ paddingTop: 30 }}>
                                <Echarts option={this.state.option }/>
                            </Col>
                            <Col span={5} style={{ paddingRight: '1.7%'}}>
                                <Row type="flex" justify="end" className='output-button'>
                                    <Button size='large'
                                        style={{ fontSize: 14}}
                                        onClick={this.export.bind(this, this.state.allDataSource, ['分部名称', '请求量'], sumMaxData)}
                                    >导出列表</Button>
                                </Row>
                                <Table 
                                    className='output-table'
                                    dataSource={this.state.allDataSource}
                                    columns={columnAll}
                                    scroll={{ y: 600 }}
                                    pagination={false}
                                    rowKey={record => record.x}
                                />
                            </Col>
                        </Row>
                        </Spin>
                    </TabPane>}
                    <TabPane tab={'分部权限'} key={'2'}>
                    <Spin spinning={partLoading} >
                        <Form onSubmit={this.search}>
                            <Row>
                                <Col span={6}>
                                    <FormItem
                                        {...formItemLayout}
                                        label="通道号"
                                    >
                                        {getFieldDecorator('distNum')(
                                            <Input maxLength={255} />
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={6}>
                                    <FormItem
                                        {...formItemLayout}
                                        label="版本号"
                                    >
                                        {getFieldDecorator('version', {
                                            rules: [{
                                                validator: this.validateVersion
                                            }],
                                        })(
                                            <Input maxLength={250} />
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={6}>
                                    <FormItem
                                        {...formItemLayout}
                                        label="序列号"
                                    >
                                        {getFieldDecorator('sn', {
                                            rules: [{
                                                validator: this.validateSn
                                            }],
                                        })(
                                            <Input maxLength={250} />
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={6}>
                                    <Col span={12}>
                                        <FormItem
                                            {...formItemLayout}
                                            label="IP"
                                        >
                                            {getFieldDecorator('startIp', {
                                                initialValue: partState?"":dailyDefaultQuery.startIp,
                                                rules: [{
                                                    validator: this.checkStartIP,
                                                }],
                                            })(
                                                <Input maxLength={255} />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={2} style={{ textAlign: 'center' }}>
                                        <FormItem>
                                            <label>-</label>
                                        </FormItem>
                                    </Col>
                                    <Col span={10}>
                                        <FormItem
                                            wrapperCol={{
                                                xs: { span: 24 },
                                                sm: { span: 20 },
                                            }}
                                        >
                                            {getFieldDecorator('endIp', {
                                                rules: [{
                                                    validator: this.checkEndIP,
                                                }],
                                                initialValue: partState?"":dailyDefaultQuery.endIp
                                            })(
                                                <Input maxLength={255} />
                                            )}
                                        </FormItem>
                                    </Col>
                                </Col>
                            </Row>
                            <Row>
                                {partState && <Col span={6}>
                                    <FormItem
                                        {...formItemLayout}
                                        label="分部名"
                                    >
                                        {getFieldDecorator('partName',{
                                            initialValue: sysCompany.id
                                        })(
                                            <Select
                                                showSearch
                                                style={{ width: '100%' }}
                                                optionFilterProp="children"
                                                onSelect={this.partNameSelect}
                                                filterOption={true}
                                            >
                                                {partNameOptions}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>}
                                <Col span={6}>
                                    <FormItem
                                        {...formItemLayout}
                                        label="时间"
                                    >
                                        {getFieldDecorator('queryMonth', {
                                            initialValue: moment(defaultQuery.queryMonth, dateFormat)
                                        })(
                                            <MonthPicker
                                                disabledDate={this.disabledDate}
                                                style={{ width: '100%' }}
                                                format={'YYYY-MM'}
                                                allowClear={false}
                                            />
                                        )}
                                    </FormItem>
                                </Col>
                                <Col {...Constant.BUTTONSPAN} className='count-button-margin'>
                                    <FormItem>
                                        <Button type="primary" htmlType="submit">查询</Button>
                                        <Button type="default" onClick={this.reset} >重置</Button>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                        <Row>
                            <Col span={19} style={{ paddingTop: 30 }}>
                                <Echarts option={this.state.option }/>
                            </Col>
                            <Col span={5} style={{ paddingRight: '1.7%'}}>
                                <Row type="flex" justify="end" className='output-button'>
                                    <Button 
                                        size='large' style={{ fontSize: 14}}
                                        onClick={this.export.bind(this, this.state.currentDataSource, ['日期', '请求量'],partMaxData)}
                                    >导出列表</Button>
                                </Row>
                                <Table 
                                    className='output-table'
                                    dataSource={this.state.currentDataSource}
                                    columns={columnCurrent}
                                    scroll={{ y: 600 }}
                                    pagination={false}
                                    rowKey={record => record.x}
                                />
                            </Col>
                        </Row>
                        </Spin>
                    </TabPane>
                </Tabs>}
                {!flag && <div>{Constant.STATISTICS_NO_PERMISSION}</div>}
            </div>
        );
    }
}

const RequestInfoForm = Form.create()(RequestInfo);
export default RequestInfoForm;